<script lang="ts" setup>

import { ref, nextTick } from 'vue';
const pwdInfo = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
});

const checkPwd = (rule, value, callbak) => {
    if (value === '') {
        callbak(new Error('请再次确认密码'))
    } else if (value !== pwdInfo.value.new_pwd) {
        callbak(new Error('请确保两次输入的密码一样'))
    } else {
        callbak()
    }
}
const rules = {
    old_pwd: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        {min: 5, max: 16, message: '长度为5-16位非空字符', trigger: 'blur'}
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { pattern: /^\S{5,16}$/, message: '长度为5-16位非空字符', trigger: 'blur'}
    ],
    re_pwd: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { validator: checkPwd, trigger: 'blur' }
    ]
}

// 重置
// 获取表单引用
const formRef = ref(); // 添加这行,同时添加到el-form里
const clearData = () => {
    pwdInfo.value.old_pwd = '';
    pwdInfo.value.new_pwd = '';
    pwdInfo.value.re_pwd = '';
    formRef.value?.resetFields(); // 使用resetFields方法
}

import { userPasswordUpdateService } from '@/api/user';
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/stores/token';
const tokenStore = useTokenStore();
import { useRouter } from 'vue-router';
const router = useRouter();
const updatePassword = async() => {
    // 修改密码
    let result = await userPasswordUpdateService(pwdInfo.value);
    ElMessage.success(result.message? result.message: "密码修改成功");
    // 移除token
    tokenStore.removeToken();
    // 跳转回登录页面
    router.push('/login');
}

</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>重置密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form ref="formRef" :model="pwdInfo" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="原密码" prop="old_pwd">
                        <el-input type="password" v-model="pwdInfo.old_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input type="password" v-model="pwdInfo.new_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="re_pwd">
                        <el-input type="password" v-model="pwdInfo.re_pwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updatePassword">提交修改</el-button>
                        <el-button @click="clearData">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>